/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.util;

/**
 * This class implements a custom class loader to enable class
 * definition and resolution.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
public final class CustomClassLoader extends ClassLoader {

    /**
     * Instance that should be used when it is necessary to ensure that some
     * classes can reach each other.
     */
    public static final CustomClassLoader INSTANCE =
        new CustomClassLoader(CustomClassLoader.class.getClassLoader());

    /**
     * Constructs a class loader with parent for delegation.
     * @param parent parent class loader used for delegation
     */
    private CustomClassLoader(final ClassLoader parent) {
        super(parent);
    } // end constructor(ClassLoader)

    /**
     * Defines and resolves the passed bytecode such that the returned
     * class is fully usable.
     * @param name class name
     * @param code class bytecode
     * @return class corresponding to given bytecode
     */
    public Class defineAndResolve(final String name, final byte[] code) {
        final Class res = defineClass(name, code, 0, code.length);
        resolveClass(res);
        return res;
    } // end method 'defineAndResolve(String, byte[])'

} // end class 'CustomClassLoader'
